/*
 * MarshallTimestamp.java
 *
 * Created on July 23, 2007, 1:21 PM
 *
 * Copyright (C) 2007 Akhmad Fathonih (akhmadf@gmail.com)
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

package com.gamatechno.anybinding.marshaller;

import com.gamatechno.anybinding.marshaller.*;
import com.gamatechno.anybinding.util.Converter;
import java.util.Calendar;

/**
 *
 * @author geek
 */
public class MarshallTimestamp implements Marshallable<Calendar>{
    
    /**
     * Creates a new instance of MarshallTimestamp
     */
    public MarshallTimestamp() {
        // Last Used
        
    }

    public byte[] serialized(Calendar data) {
        byte[] res =new byte[5];
        res[0] = (byte) data.get(Calendar.DATE);
        res[1] = (byte) data.get(Calendar.MONTH);
        int year = Integer.valueOf(String.valueOf(data.get(Calendar.YEAR)).substring(2)).intValue();
        res[2] = (byte) year;
        res[3] = (byte) data.get(Calendar.HOUR_OF_DAY);
        res[4] = (byte) data.get(Calendar.MINUTE);
        
        return res;
    }

    public Calendar unserialized(byte[] data) {
        Calendar cal = Calendar.getInstance();
        if (!Converter.byteToHexString(data).equals("0000000000")) {
            String year_1 = new String(""+cal.get(cal.YEAR)).substring(0, 2);
            String year_2 = "" + (0x000000ff & (int) data[2]);
            if (year_2.length() == 1) {
                year_2 = "0"+year_2;
            }
            cal.set(cal.DATE, (int) data[0]);
            cal.set(cal.MONTH, ((int) data[1])-1);
            cal.set(cal.YEAR, Integer.parseInt(year_1+year_2));
            cal.set(cal.HOUR_OF_DAY, (int) data[3]);
            cal.set(cal.MINUTE, (int) data[4]);
        }
        return cal;
    }

    public boolean isInitialized() {
        return true;
    }
    
}
